<?php

namespace App\Service;

use App\Models\SearchHistoryModel;
use App\Models\SearchTermModel;
use Carbon\Carbon;

class SearchTermService
{
    public function addSearchHistory($keyword, $userId)
    {
        $params = [
            'search_query' => $keyword,
            'user_id' => $userId,
            'search_time' => Carbon::now()->toDateTimeString()
        ];
        return SearchHistoryModel::commit($params);
    }

    public function addSearchTerm($keyword): bool
    {
        $timePeriod = self::getTimePeriod();
        return SearchTermModel::incrementCount($keyword, $timePeriod);
    }

    public function queryHistory($userId)
    {
        return SearchHistoryModel::getByUserId($userId, 5);
    }

    public function querySearchTerm($limit = 10, $timePeriod = null)
    {
        $timePeriod = $timePeriod ?? self::getTimePeriod();
        return SearchTermModel::getByTimePeriod($timePeriod, $limit);
    }

    public static function getTimePeriod(): string
    {
        return Carbon::now()->format('Y-m-d');
    }
}
